package com.duobaoyu.dby.supply.message.listener.hander.order;

import com.alibaba.fastjson.JSON;
import com.duobaoyu.dby.supply.biz.client.boundary.order.OrderBoundaryClient;
import com.duobaoyu.dby.supply.biz.client.boundary.order.bean.bo.BatchCalcOrderFreightResultBO;
import com.duobaoyu.dby.supply.biz.client.boundary.order.bean.bo.OrderBO;
import com.duobaoyu.dby.supply.biz.client.boundary.order.bean.bo.OrderQueryInBO;
import com.duobaoyu.dby.supply.biz.client.boundary.order.bean.bo.UpdateOrderBO;
import com.duobaoyu.dby.supply.biz.producer.constant.SupplyChainMQConstants;
import com.duobaoyu.dby.supply.biz.producer.message.OrderEstimateFreightCalcMessage;
import com.duobaoyu.dby.supply.biz.service.order.OrderService;
import com.duobaoyu.dby.supply.core.dinger.annotation.DingerTalk;
import com.duobaoyu.dby.supply.core.rocketmq.handler.AbstractClusterMessageHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 计算预估运费消息处理器
 *
 * @author chenms
 * @date 2023/10/07 10:58
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderEstimateFreightCalcMessageHandler extends AbstractClusterMessageHandler<OrderEstimateFreightCalcMessage> {

    private final OrderService orderService;
    private final OrderBoundaryClient orderBoundaryClient;

    @Override
    public String getTopic() {
        return SupplyChainMQConstants.SupplyChainTopic.ORDER_TOPIC;
    }

    @Override
    public String getTag() {
        return SupplyChainMQConstants.SupplyChainTopic.OrderTag.ESTIMATE_FREIGHT_AMOUNT;
    }

    @Override
    @DingerTalk(title = "供应链预估运费计算消息Consumer")
    public boolean messageHandler(OrderEstimateFreightCalcMessage orderConfirmMessage, MessageExt messageExt) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("收到预估运费计算消息: {}", JSON.toJSONString(orderConfirmMessage));
            }
            List<String> orderSnList = orderConfirmMessage.getOrderSnList();
            if (CollectionUtils.isEmpty(orderSnList)) {
                log.info("计算预估运费,消息中没有订单号");
                return true;
            }
            List<OrderBO> orders = orderService.list(OrderQueryInBO.builder().orderSnList(orderSnList).returnProduct(Boolean.TRUE).returnConsignee(Boolean.TRUE).build());
            if (CollectionUtils.isEmpty(orders)) {
                log.info("订单数据不存在: orderSnList={}", orderSnList);
                return true;
            }
            BatchCalcOrderFreightResultBO batchCalcOrderFreightResult = orderBoundaryClient.batchCalcOrderFreight(orders);
            if (batchCalcOrderFreightResult.existsCalcFailureOrder()) {
                log.info("计算订单运费失败: {}", batchCalcOrderFreightResult.getErrorMessage(null));
            }
            // 计算成功订单运费
            Map<String, BigDecimal> orderFreight = batchCalcOrderFreightResult.getOrderFreight();
            orderFreight.forEach((orderSn, estimateFreight) -> {
                UpdateOrderBO updateOrder = UpdateOrderBO.builder().orderSn(orderSn).estimateFreight(estimateFreight).build();
                orderService.updateOrderByOrderSn(updateOrder);
            });
        } catch (Exception e) {
            log.warn("计算预估运费异常: message={}", orderConfirmMessage, e);
        }
        return true;

    }
}
